package com.taotao.controller;
/**
 * 图片上传controller
 * @author 好好学习天天向上
 *
 */

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.utils.FastDFSClient;

import utils.JsonUtils;
@Controller
public class PictureController {
	
	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/pic/upload",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String uploadPic(MultipartFile uploadFile) {
		//获得文件扩展名
		String originalFilename = uploadFile.getOriginalFilename();
		String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
		//使用工具类将文件上传到fastDfs 图片服务器上
		FastDFSClient fastDFSClient;
		try {
			fastDFSClient = new FastDFSClient("classpath:resource/fast_dfs.conf");
			String url = fastDFSClient.uploadFile(uploadFile.getBytes(), ext);
			//从配置文件中取图片服务器的url前面部分.(网络地址)
			//创建返回结果对象
			Map result =new HashMap();
			result.put("error", 0);
			result.put("url", IMAGE_SERVER_URL+url);
			return JsonUtils.objectToJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			Map result =new HashMap();
			result.put("error", 1);
			result.put("messager", "图片上传失败");
			return JsonUtils.objectToJson(result);
		}
		
	}
}
